#include "linkedList.h"

void enqueue(queue_t* unitQueue, int data, coordinate_t point) {
	node* queueFront = unitQueue->front;
	node* queueRear = unitQueue->rear;

	node* queueNode = (node*) malloc(sizeof(node));

	queueNode->prev = queueRear->prev;
	queueNode->next = queueRear;

	queueRear->prev->next = queueNode;
	queueRear->prev = queueNode;

	queueNode->data = data;
	queueNode->point.x = point.x;
	queueNode->point.x = point.y;
	unitQueue->length++;
}

int dequeue(queue_t* unitQueue) {
	node* queueFront = unitQueue->front;
	node* queueRear = unitQueue->rear;

	node* deQueueNode;

	int data;
	if (queueFront->next != queueRear) {
		deQueueNode = queueFront->next;

		queueFront->next = deQueueNode->next;
		deQueueNode->next->prev = queueFront;

		data = deQueueNode->data;

		free(deQueueNode);
		unitQueue->length--;
		return data;
	}
	else {
		printf("queue is empty\n");
		return -1;
	}

}

/* 
	how to use  :
	queue_t* unitQueue = NULL;
	initQueue(unitQueue);

	and then... enqueue(...), dequeue(...)
	unitqueue->front->data is queue's length
*/	
void initQueue(queue_t* &unitQueue) {
	unitQueue = (queue_t*) malloc(sizeof(queue_t));

	node* queueFront = (node*) malloc(sizeof(node));
	node* queueRear = (node*) malloc(sizeof(node));
	unitQueue->length = 0;

	queueFront->next = queueRear;
	queueFront->prev = NULL;
	queueRear->next = NULL;
	queueRear->prev = queueFront;

	unitQueue->front = queueFront;
	unitQueue->rear = queueRear;
}


void freeQueue(queue_t* &unitQueue) {	
	if (unitQueue->front->data == 0) {
		free(unitQueue->front);
		free(unitQueue->rear);
		free(unitQueue);
	}
	else {
		while (dequeue(unitQueue) != -1)
		{
		}
		free(unitQueue->front);
		free(unitQueue->rear);
		free(unitQueue);		
	}
}
